import {ElMessage, ElMessageBox} from 'element-plus'

export class Toast {
  show(text = '', config = {}) {
    // config.type = config.type!=undefined?config.type:'info'
    // 默认关闭时间
    config.duration = config.duration != undefined ? config.duration : 1800
    // 默认显示可关闭图标
    config.showClose = config.showClose != undefined ? Boolean(config.showClose) : true
    // 默认合并相同内容
    config.grouping = config.grouping != undefined ? Boolean(config.grouping) : true
    config.message = text
    ElMessage(config)
  }

  success(text = '', config = {}) {
    config.type = 'success'
    this.show(text, config)
  }

  error(text = '', config = {}) {
    config.type = 'error'
    this.show(text, config)
  }

  warn(text = '', config = {}) {
    config.type = 'warning'
    this.show(text, config)
  }
}

export const toast = new Toast()

export class Message {
  async show(title = '', text = '', config = {}, type = 'confirm') {
    config.title = title
    // config.type = config.type == undefined ? 'info' : config.type
    config.draggable = true
    try {
      return new Promise((resolve, reject) => {
        ElMessageBox[type](text, config.type, config).then(row => {
          if (typeof row == "string") {
            resolve(Boolean(row))
          } else {
            // 带输入框的。确认时返回的是文本，取消时返回是Boolean类型的false，
            // 判断用typeof res == 'boolean'，不能用if(res==false){}
            if (type == 'prompt') {
              resolve(row.value ? row.value : '')
            }
          }
          resolve(true)
        }).catch((row) => {
          resolve(false)
        })
      })
    } catch (err) {
      console.log('弹窗异常：', err)
      return false
    }
  }

  warn(title = '', text = '', config = {}) {
    config['showConfirmButton'] = true
    config['showCancelButton'] = true
    config['cancelButtonText'] = '取消'
    config['confirmButtonText'] = config['confirmButtonText']==undefined?'确认':config['confirmButtonText']
    config.type = 'warning'
    return this.show(title, text, config)
  }

  sureW(title = '', text = '', config = {}) {
    config['showConfirmButton'] = true
    config['confirmButtonText'] = '确认'
    config.type = 'warning'
    return this.show(title, text, config, 'alert')
  }

  // 带提交内容
  input(title = "", text = '', placeholder = '', config = {}) {
    config['showConfirmButton'] = true
    config['showCancelButton'] = true
    config['cancelButtonText'] = '取消'
    config['confirmButtonText'] = '确认'
    config['inputPlaceholder'] = placeholder
    return this.show(title, text, config, 'prompt')
  }


}

export const message = new Message()